//
//  YYPlayingViewController.m
//  音乐播放器
//
//  Created by zpy on 15/11/28.
//  Copyright © 2015年 zpy. All rights reserved.
//

#import "YYPlayingViewController.h"
#import "YYMusic.h"
#import "YYMusicTool.h"
#import "YYAudioTool.h"
#import "YYLrcView.h"
@interface YYPlayingViewController ()<AVAudioPlayerDelegate>
// 记录正在播放的音乐
@property(nonatomic, strong) YYMusic *playingMusic;
// 播放器
@property(nonatomic, strong) AVAudioPlayer *player;



@property (weak, nonatomic) IBOutlet UILabel *songLabel;
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
@property (weak, nonatomic) IBOutlet UIImageView *singerIcon;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *silderButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sliderLeftConstraint;

@property (weak, nonatomic) IBOutlet UILabel *showTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *playOrPauseButton;
@property (weak, nonatomic) IBOutlet YYLrcView *lrcView;

// 进度条定时器
@property(nonatomic,strong) NSTimer *progressTimer;
// 歌词定时器
@property(nonatomic,strong) CADisplayLink *lrcTimer;

@end

@implementation YYPlayingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showTimeLabel.layer.cornerRadius = 5.0;
    self.showTimeLabel.layer.masksToBounds = YES;
}
#pragma mark 对音乐播放的控制
// 开始播放音乐
-(void) startPlayingMusic {
// 1 拿到正在播放的 音乐
    YYMusic *playingMusic = [YYMusicTool playingMusic];
    
    self.playingMusic = playingMusic;
    // 2 设置界面数据
    self.songLabel.text = playingMusic.name;
    self.singerLabel.text = playingMusic.singer;
    self.singerIcon.image = [UIImage imageNamed:playingMusic.icon];

    // 设置歌词文件名称
    self.lrcView.lrcName = playingMusic.lrcname;
    
    self.player = [YYAudioTool playMusicWithName:playingMusic.filename];
    self.totalTimeLabel.text = [self stringWithTime:self.player.duration];
    self.player.delegate = self;
    // 添加定时器
    [self addProgressTimer];
    // 避免切歌还显示上一曲的进度,强制更新info
    [self updateInfo];
    
    [self addLrcTimer];
    [self updateLrcTime];
    // 改变播放按钮的状态
    self.playOrPauseButton.selected = NO;
}
// 停止播放音乐
-(void)stopPlayingMusic {
// 清楚前一个播放歌曲的信息
    self.songLabel.text = nil;
    self.singerLabel.text = nil;
    self.singerIcon.image = [UIImage imageNamed:@"play_cover_pic_bg"];
    self.totalTimeLabel.text = nil;
    // 停止音乐
    [YYAudioTool stopMusicWithName:self.playingMusic.filename];
    // 移除进度  歌词定时器什么的
    
 }
#pragma mark 对控制器的操作
// 跳转操作
-(void)show {
// 判断新点击的cell 是否是同一首音乐
    if (self.playingMusic && self.playingMusic != [YYMusicTool playingMusic]) {
        [self stopPlayingMusic];
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    window.userInteractionEnabled = NO;
    
    self.view.frame = window.bounds;
    self.view.backgroundColor = [UIColor redColor];
    [window addSubview:self.view];
    // 通过设置view的frame  来添加动画   y  是分类中的y
    //self.view.bounds.origin.y = self.view.frame.size.height;
    self.view.y = self.view.height;
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = 0;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
        // 开始播放音乐
        [self startPlayingMusic];
    }];
}
// 退出按钮
- (IBAction)exit {
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = self.view.height;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
    }];
}
#pragma mark 对定时器的操作
/**
 *  进度条指示器
 */
// 添加进度条的定时器
-(void) addProgressTimer {

    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}
// 移除进度条的指示器
-(void) removeProgressTimer {

    [self.progressTimer invalidate];
    self.progressTimer = nil;
}
// 添加歌词定时器
- (void)addLrcTimer {
    if (self.lrcView.hidden) {
        return;
    }
    self.lrcTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrcTime)];
    [self.lrcTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    [self updateLrcTime];
}
//
- (void)removeLrcTimer {
    [self.lrcTimer invalidate];
    self.lrcTimer = nil;
}
#pragma mark 更新进度条的内容
-(void) updateInfo {

// 计算播放的比例
    CGFloat progressRatio = self.player.currentTime / self.player.duration;
    self.sliderLeftConstraint.constant = progressRatio * (self.view.width - self.silderButton.width);
    // 更新滑块的文字
    NSString *currentTimeStr = [self stringWithTime:self.player.currentTime];
    [self.silderButton setTitle:currentTimeStr forState:UIControlStateNormal];
    
    
}
- (void)updateLrcTime {
    self.lrcView.currentTime = self.player.currentTime;

}
// 点击进度条的背景 更新播放进度
- (IBAction)tapProgressBackground:(UITapGestureRecognizer *)sender {
   // 1 获取用户点击的位置
    CGPoint point = [sender locationInView:sender.view];
    // 更新滑块的约束
    if (point.x <= self.silderButton.width * 0.5) {
        self.sliderLeftConstraint.constant = 0;
    } else if (point.x >= self.view.width - self.silderButton.width * 0.5) {
        self.sliderLeftConstraint.constant = self.view.width - self.silderButton.width - 1;
    } else {
        self.sliderLeftConstraint.constant = point.x - self.silderButton.width * 0.5;
    }
    // 3.改变当前播放的时间
    CGFloat progressRatio = self.sliderLeftConstraint.constant / (self.view.width - self.silderButton.width);
    CGFloat currentTime = progressRatio * self.player.duration;
    self.player.currentTime = currentTime;
    // 4
    [self updateInfo];
    
}

- (IBAction)panSilderButton:(UIPanGestureRecognizer *)sender {
    // 获取用户的拖拽位移
   CGPoint point = [sender translationInView:sender.view];
    [sender setTranslation:CGPointZero inView:sender.view];
    // 改变按钮的约束
    if (self.sliderLeftConstraint.constant + point.x <= 0) {
        self.sliderLeftConstraint.constant = 0;
    }else if (self.sliderLeftConstraint.constant + point.x >= self.view.width - self.silderButton.width){
        self.sliderLeftConstraint.constant = self.view.width - self.silderButton.width - 1;
    }else{
    
        self.sliderLeftConstraint.constant += point.x;
    }
    // 获取拖拽进度对应的时间
    CGFloat progressRatio = self.sliderLeftConstraint.constant / (self.view.width - self.silderButton.width);
    CGFloat currentTime = progressRatio * self.player.duration;
    // 更新button 文字
    NSString *currentTimeStr = [self stringWithTime:currentTime];
    [self.silderButton setTitle:currentTimeStr forState:UIControlStateNormal];
    self.showTimeLabel.text = currentTimeStr;
    
    // 监听拖拽手势的状态
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self removeProgressTimer];
        self.showTimeLabel.hidden = NO;
    }else if (sender.state == UIGestureRecognizerStateEnded){
    // 更新播放时间
        self.player.currentTime = currentTime;
        [self addProgressTimer];
        self.showTimeLabel.hidden = YES;
        
    }
}
#pragma mark 播放控制按钮功能实现
- (IBAction)playOrPauseButtonClick {
    self.playOrPauseButton.selected = !self.playOrPauseButton.selected;
    if (self.player.playing) {
        [self.player pause];
        [self removeProgressTimer];
        [self removeLrcTimer];
    } else {
        [self.player play];
        [self.player play];
        [self addLrcTimer];
    }
}
- (IBAction)previousButton {
    [self stopPlayingMusic];
    [YYMusicTool previousMusic];
    [self startPlayingMusic];
}
- (IBAction)nextButton {
    [self stopPlayingMusic];
    [YYMusicTool nextMusic];
    [self startPlayingMusic];
}
// 切换歌词或图片
- (IBAction)SwitchButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.lrcView.hidden = !self.lrcView.hidden;
    
    if (self.lrcView.hidden) {
        [self removeLrcTimer];
    } else {
        [self addLrcTimer];
    }
}


#pragma mark AVAudioPlayer 的一些代理方法

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    if (flag) {
        [self nextButton];
    }
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{

    [self playOrPauseButtonClick];
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player{

    [self playOrPauseButtonClick];
}
#pragma mark 计算歌曲时间的私有方法

-(NSString *) stringWithTime: (NSTimeInterval)time {

    NSInteger minute = time / 60;
    NSInteger second = (NSInteger)time % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld",minute,second];
    
}

@end
